package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Dto.SetmealDto;
import com.itheima.reggie.dao.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetdmealService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SetdmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetdmealService {


    @Autowired
    private SetmealDishService setmealDishService;


    //保存
    @Override
    public void saveWithD(SetmealDto setmealDto) {
        //保存菜品基本信息
        this.save(setmealDto);

        //List集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //setmealDishes中的方法
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }

    //回显数据
    @Override
    public SetmealDto SelectById(Long id) {
        Setmeal setmeal =this.getById(id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getDishId,id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(list);

        return setmealDto;

    }

    //修改
    @Override
    public void UpdataWithS(SetmealDto setmealDto) {
        //套餐信息更新
        this.updateById(setmealDto);

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());

        setmealDishService.remove(queryWrapper);

        List<SetmealDish> list = setmealDto.getSetmealDishes();

        list = list.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());

            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(list);
    }
}
